const {Service} = require('egg')
const nodeMailer = require('nodemailer')
const fse = require('fs-extra')
const path = require('path')
const userEmail = 'hnlyh2234@163.com'
const transporter = nodeMailer.createTransport({
  service: '163',
  secureConnection: true,
  auth:{
    user:userEmail,
    pass:'AGKXOONJWDYXLIXM'
  }
})

class ToolService extends Service{
  async mergeFile(filePath,filehash,size){
    const chunkDir = path.resolve(this.config.UPLOAD_DIR,filehash)//切片的文件夹
    let chunks = await fse.readdir(chunkDir)
    chunks.sort((a,b)=>a.split('-')[1]-b.split('-')[1])
    chunks = chunks.map(cp=>path.resolve(chunkDir,cp))
    await this.mergeChunks(chunks,filePath,size,chunkDir)
  }
  async mergeChunks(files,dest,size,chunkDir){
    // const pipStream = (filePath,writeStream)=>new Promise((resolve)=>{
    //   const readSteam = fse.createReadStream(filePath)
    //   readSteam.on('end',()=>{
    //     fse.unlinkSync(filePath)
    //     resolve()
    //   })
    //   readSteam.pipe(writeStream,{ end: false })
    // })
    // await Promise.all(
    //   files.map((file,index)=>{
    //     pipStream(file,fse.createWriteStream(dest,{
    //       start:index*size,
    //       end:(index+1)*size
    //     }))
    //   })
    // )
    let writeStream = fse.createWriteStream(dest); 
    let mergedChunkNum = 0
    const chunkCount = files.length
    return mergeCore()
  	//闭包保存非递归数据
    function mergeCore(){
      //结束标志为已合并数量大于总数（mergedChunkNum从0开始）
      if (mergedChunkNum >= chunkCount){
        fse.rmdir(chunkDir);
        return
      }
      const curChunkReadStream = fse.createReadStream(files[mergedChunkNum]);
      //将readStream 写入 writeStream
      curChunkReadStream.pipe(writeStream, { end: false }); //end = false 则可以连续给writeStream 写数据
      curChunkReadStream.on("end", () => {
          //readStream 传输结束 则 递归 进行下一个文件流的读写操作
          fse.unlinkSync(files[mergedChunkNum]) //删除chunkFile
          mergedChunkNum += 1
          mergeCore();
      });
    }
  }
  async sendMail(email,subject,text,html){
    const mailOptions = {
      from: userEmail,
      cc: userEmail,
      to:email,
      subject,
      text,
      html
    }
    try{
      await transporter.sendMail(mailOptions)
      return true
    }catch(err){
      console.log('email err',err);
      return false
    }
  }
}

module.exports = ToolService